
function isContainerEle(type: string) {
  // 判断是否是容器组件
  return ['Grid', 'Tab'].includes(type)
}

function getContainerTag(compName: string, isChild: boolean = false) {
  // 获取容器的标签
  let tag = ''
  switch (compName) {
    case 'Grid':
      tag = isChild ? 'e-col' : 'e-row'
      break
    case 'Tab':
      tag = isChild ? 'eTabPane' : 'eTabs'
      break
  }
  return tag
}

function getValidProps(_props: any, component?: string) {
  // 获取有效的组件属性
  const props = _props || {}
  const res: Record<string, any> = {}
  Object.keys(props).forEach((key: string) => {
    if (!/^_/.test(key) && typeof props[key] !== 'object') {
      if (component === 'eRadioGroup' && key === 'type' && props[key] === 'default') {
        // 单选框type为default时，不设置，否则会报错
      } else if (component === 'eSwitch' && key === 'type') {
        if (props[key] === 'number') {
          res['true-value'] = 1
          res['false-value'] = 0
        } else {
          res['true-value'] = true
          res['false-value'] = false
        }
      } else if (component === 'eTimePicker' && key === 'steps') {
        try {
          const parsedArray = JSON.parse(props[key])
          if (Array.isArray(parsedArray)) {
            res[key] = parsedArray
          } else {
            res[key] = []
          }
        } catch (e) {
          res[key] = []
        }
      } else {
        res[key] = props[key]
      }
    } else if (key === '_style') {
      res['style'] = props[key]
    } else if (key === '_className') {
      res['class'] = props[key]
    }
  })
  return res
}

// 首字母大写
function capitalize(str: string) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

function getFuncFromString(funcStr: any): (...args: any[]) => any {
  let func = () => {}
  if (funcStr) {
    if (typeof funcStr === 'string' && funcStr.includes('function')) {
      func = eval(`(${funcStr})`)
    } else if(typeof funcStr === 'function') {
      func = funcStr
    }
  }
  return func
}

function loadStyleString(id: string, styleStr: string) {
  const style = document.createElement('style')
  style.setAttribute('id', `${id}_page_style`)
  style.innerHTML = styleStr
  document.head.appendChild(style)
}

function unLoadStyle(id: string) {
  const style = document.getElementById(`${id}_page_style`)
  if (style) {
    document.head.removeChild(style)
  }
}

function createCancellablePromise(duration: number = 20000) {
  let cancel = () => { }
  const promise = new Promise((resolve) => {
    const timeoutId = setTimeout(() => {
      resolve(null)
    }, duration)

    cancel = () => {
      clearTimeout(timeoutId)
      resolve(null)
    }
  })

  return { promise, cancel }
}

function convertValue(item: any) {
  const value = item.dataModel.defaultValue
  const component = toCamelCase(item.component)
  if (!value) {
    return (['eCheckboxGroup'].includes(component) || (component === 'eSelect' && item.props.multiple))
      ? []
      : null
  }
  // 检查是否是数组的字符串
  try {
    const parsedArray = JSON.parse(value)
    if (Array.isArray(parsedArray)) {
      return parsedArray
    }
  } catch (e) {
    // 如果不是有效的JSON数组字符串，继续检查其他类型
  }
  // 检查是否是布尔值字符串
  if (value === 'true') {
    return true
  } else if (value === 'false') {
    return false
  }
  // 检查是否是数字字符串
  const parsedNumber = Number(value)
  if (!isNaN(parsedNumber)) {
    return parsedNumber
  }
  // 如果没有匹配任何情况，返回原始字符串
  return value
}

function withExtraParams(handler: (...args: any[]) => any, ...args: any[]) {
	return (...originalArgs: any[]) => {
		handler.call(null, ...args, ...originalArgs)
	}
}

function toCamelCase(componentName: string) {
  return componentName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
}

function isEmpty(value: any) {
  return value === undefined || value === null || value === ''
}

export {
  isContainerEle,
  getContainerTag,
  getValidProps,
  capitalize,
  getFuncFromString,
  loadStyleString,
  unLoadStyle,
  createCancellablePromise,
  convertValue,
  withExtraParams,
  toCamelCase,
  isEmpty
}